﻿using System;
using System.Data.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;
using LZMA;
using System.Collections.Generic;

[AllowedRole("IsAdmin")]
public class KBDocumentController : EntityListController<KBDocument,NotarialServiceDataContext>
{
    bool create = false;

    protected override void EntityLoaded(NotarialServiceDataContext dc, KBDocument entity)
    {
        LayoutPath = "~/views/layouts/popup.haml";
        
        RegisterScript("markitup/jquery.markitup.pack.js", "markitup/sets/html/set.js");
        RegisterStylesheet("kbdocument/kb.css", "../js/markitup/skins/simple/style.css", "../js/markitup/sets/html/style.css");

        //RegisterScript("jquery.ajax-form.js", "ckeditor/ckeditor.js", "ckeditor/adapters/jquery.js");
        //RegisterStylesheet("kbdocument/kb.css");

        ViewData["whitebg"] = true;
        if (entity.Id == 0 && !string.IsNullOrEmpty(Request["parentid"]))
            entity.ParentId = Convert.ToInt32(Request["parentid"]);
            
        string searchString = "";
        if (!String.IsNullOrEmpty(Request["searchstring"]))
            searchString = Request["searchstring"].Trim();
        ViewData["searchstring"] = searchString;

        int selectedFolderId = 0;
        if (!String.IsNullOrEmpty(Request["selectedfolderid"]))
            Int32.TryParse(Request["selectedfolderid"], out selectedFolderId);
        ViewData["selectedfolderid"] = selectedFolderId;
    }

    public override void View(string entityid)
    {
        if (!string.IsNullOrEmpty(Request["print"]))
            ViewData["print"] = true;
        TemplatePath = "~/views/kbdocument/view.haml";
        base.View(entityid);
    }

    [AllowedRole("kbadmin")]
    public override void Create()
    {
        base.Create();
    }

    [AllowedRole("kbadmin")]
    public void Edit(string entityid)
    {
        base.View(entityid);
    }

    [AllowedRole("kbadmin")]
    public override void Delete()
    {
        base.Delete();
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, KBDocument entity)
    {
        create = (entity.Id == 0);

        UploadFiles(dc, entity);
    }

    protected override void AfterSubmit(NotarialServiceDataContext dc, KBDocument entity)
    {
        Logger.WriteLog(dc, (create) ? LogOperationType.KbDocumentCreate : LogOperationType.KbDocumentChange, (Session["User"] as User).Id, null, null);
    }

    protected override void EntityDeleted(NotarialServiceDataContext dc, List<KBDocument> deleted)
    {
        foreach (var entity in deleted)
            Logger.WriteLog(dc, LogOperationType.KbDocumentDelete, (Session["User"] as User).Id, null, null);
    }

    private void UploadFiles(NotarialServiceDataContext dc, KBDocument doc)
    {
        if (Request.Files.Count > 0)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                var fileContent = RequestHelper.GetPostedFileContent(file);
                if (fileContent.Length == 0) continue;

                var df = new KBDocumentFile
                             {
                                 Data =  fileContent,
                                 CreatorId = ((User) ViewData["user"]).Id,
                                 Name = Path.GetFileName(file.FileName),
                             };
                doc.KBDocumentFiles.Add(df);
            }
        }
    }

    [AllowedRole("kbadmin")]
    public void RemoveFile(string fileid)
    {
        using (var dc = new NotarialServiceDataContext())
        {
            int fid;
            Int32.TryParse(fileid, out fid);

            var file = dc.KBDocumentFiles.Single(f => f.Id == fid);

            try
            {
                dc.KBDocumentFiles.DeleteOnSubmit(file);
                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                RenderJSON(new AJAXResult(ex));
                return;
            }

            var r = new AJAXResult {Id = fileid};
            RenderJSON(r);
        }
    }

    public void ViewFile(string fileid)
    {
        using (var dc = new NotarialServiceDataContext())
        {
            int fid;
            Int32.TryParse(fileid, out fid);

            var file = dc.KBDocumentFiles.Single(f => f.Id == fid);

            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + file.Name);
            Response.HeaderEncoding = Encoding.GetEncoding("windows-1251");
            Response.ContentEncoding = Encoding.GetEncoding("windows-1251");

            byte[] bytes;
            try
            {
                bytes = Extractor.ExtractBytes(file.Data.ToArray());
            }
            catch
            {
                bytes = file.Data.ToArray();
            }
            Response.BinaryWrite(bytes);

            Response.Flush();
            Response.End();
        }
    }
}